package com.nowoe.aop;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @author 倚栏听风 2023/9/16 11:27
 */
public class ProceedingJoinPoint {
    private List<Advisor> advisors;//切面集合
    private Object target; //目标对象
    private Method method; //目标方法
    private Object[] args; //方法参数

    public ProceedingJoinPoint(List<Advisor> advisors, Object target, Method method, Object[] args) {
        this.advisors = advisors;
        this.target = target;
        this.method = method;
        this.args = args;
    }

    private int index = 0;

    /**
     * 一次处理一个切面 ，没更多切面，调用目标方法
     *
     * @return
     */
    public Object proceed() {
        while (index < advisors.size()) {
            //未处理完
            Advisor advisor = advisors.get(index++);
            if (!advisor.pointcut().matches(method, target.getClass())) {
                continue;
            }
            return advisor.advice().around(this);
        }
        //处理完执行方法
        try {
            method.setAccessible(true);
            return method.invoke(target, args);
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }
}
